package leetcode.offer0041;

import java.util.LinkedList;
import java.util.Queue;

public class MovingAverage {

	int size;
//	Queue<Integer> queue;
	int sum;
	int[] queue;
	int l, r;
	int len;

	public MovingAverage(int size) {
		this.size = size;
//		this.queue = new LinkedList<>();
		this.queue = new int[size];
		this.sum = 0;
		this.l = 0;
		this.r = 0;
		this.len = 0;
	}

	public double next(int val) {
		this.sum += val;
		if (this.len == size) {
			this.sum -= this.queue[l++];
			this.len--;
			l %= size;
		}
		this.len += 1;
		this.queue[r++ % size] = val;
		r %= size;
		return 1d * this.sum / this.len;
	}

	public static void main(String[] args) {
		MovingAverage movingAverage = new MovingAverage(3);
		double ans = movingAverage.next(1); // 返回 1.0 = 1 / 1
		System.out.println(ans);
		ans = movingAverage.next(10); // 返回 5.5 = (1 + 10) / 2
		System.out.println(ans);
		ans = movingAverage.next(3); // 返回 4.66667 = (1 + 10 + 3) / 3
		System.out.println(ans);
		ans = movingAverage.next(5); // 返回 6.0 = (10 + 3 + 5) / 3
		System.out.println(ans);

	}

}
